<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.serviceStateList" size="medium" class="item-gap" @change="onStateChange">
				<el-radio-button v-for="item in saleOrderStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id <= 1 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 1.5px;">{{ item.name }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<!--<jk-button class="margin-5-0 item-gap" icon="el-icon-plus" type="primary" @click="onAddBtn">新增</jk-button>-->
					<!--<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
					<jk-button v-if="!isMerge" size="small" type="warning" icon="el-icon-share" :disabled="searchParams.serviceStateList >= 2" @click="onToggleBtn(true)">合并下达</jk-button>
					<div v-else class="flex-start-center">
						<div class="item-gap"><el-button size="small" type="warning" icon="el-icon-close" @click="onToggleBtn(false)">取消</el-button></div>
						<el-button size="small" :disabled="!checkData.length" type="primary" icon="el-icon-s-promotion" @click="onJumpOrder">确定</el-button>
					</div>
				</div>
				<div class="flex-end-center-wrap">
					<jk-search-input v-model="searchParams.customerNameOrCode" placeholder="客户名称或编号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.productOrderCode" placeholder="生产订单号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.saleOrderCode" placeholder="单据编号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 10"
				:checkbox-config="{strict: true}"
				@checkbox-change="onCheckboxChange"
			>
				<vxe-table-column :visible="isMerge" fixed="left" type="checkbox" width="60" align="center"></vxe-table-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-state-bar v-if="item.keyName === 'serviceState'" :state="scope.row.serviceState" :state-list="saleOrderStateList"></jk-state-bar>
						<span v-else-if="item.keyName === 'yarnCount'">{{ scope.row.yarnCount ? Number(scope.row.yarnCount) : '' }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" field="operation" align="center" fixed="right" :width="200">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :disabled="scope.row.serviceState > 1" icon="el-icon-s-flag" class="item-gap" size="mini" type="success" @click="onReleaseBtn(scope.row)">下达</jk-button>
							<!--<jk-edit-button :permission-prefix="prefix" :disabled="scope.row.serviceState >= 3" class="item-gap" @click="onEditBtn(scope.row)"></jk-edit-button>-->
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item, index) in dropdownOption"
										:key="index"
										:command="item.code"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.serviceState !== item.allowState : false"
									>
										<span :class="item.icon" class="item-gap"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChangeOfSaveDialogState"
			@on-finish="onFinishOfSaveDialogState"
		></save-dialog>
		<release-dialog
			:data-list="checkData"
			:data-id="dataId"
			:dialog-state="releaseDialogState"
			@on-visible-change="onVisibleChangeOfReleaseDialogState"
			@on-finish="onFinishOfReleaseDialogState"
		></release-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        productionSaleOrderGetStateCount,
        productionSaleOrderDelete, productionSaleOrderGet,
        productionSaleOrderPage, productionSaleOrderClearClose, productionSaleOrderClose, productionSaleOrderDeleteItem
    } from '/src/api/production/order';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { saleOrderStateList } from '../../../utils/jk/status-option-list';
    import saveDialog from './save-dialog';
    import releaseDialog from './release-dialog';
    export default {
        name: 'SaleOrder',
        components: {
            releaseDialog,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'production:saleOrder',
                apiItem: {
                    'page': productionSaleOrderPage,
                    'delete': productionSaleOrderDelete
                },
                saleOrderStateList: [
                    ...saleOrderStateList,
                    { id: -1, name: '全部' }
                ],
                releaseDialogState: false,
                saveDialogState: false,
                dataId: null,
                tableLoading: true,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    customerNameOrCode: '',
                    productOrderCode: '',
                    productNameOrCode: '',
                    batchCode: '',
                    saleOrderCode: '',
                    serviceStateList: 0
                },
                dropdownOption: [
                    { code: 'QUERY', allowState: null, name: '详情', api: productionSaleOrderGet, color: '#2b85e4', icon: 'el-icon-view' },
                    { code: 'FINISH', allowState: null, name: '完成', api: productionSaleOrderClose, color: '#2b85e4', icon: 'el-icon-finished' },
                    { code: 'CANCEL', allowState: 3, name: '撤销', api: productionSaleOrderClearClose, color: '#2b85e4', icon: 'el-icon-close' },
                    { code: 'DELETE', allowState: 0, name: '删除', api: productionSaleOrderDeleteItem, color: '#19be6b', icon: 'el-icon-delete' }
                ],
                checkData: [],
                isMerge: false,
                pageType: 'add'
            };
        },
        methods: {
            onFinishOfReleaseDialogState() {},
            onVisibleChangeOfReleaseDialogState(e) {
                this.releaseDialogState = e;
            },
            onFinishOfSaveDialogState() {
                this.getListRequest();
                this.saveDialogState = false;
            },
            onToggleBtn() {
                this.isMerge = !this.isMerge;
                if (!this.isMerge) {
                    this.$refs.jkTable.$refs.xTable.clearCheckboxRow();
                    this.checkData = [];
                }
                this.$nextTick(() => {
                    this.$refs.jkTable.$refs.xTable.refreshColumn();
                });
            },
            validatorCheckData() {
                let ids = this.checkData.map(x => x.productName);
                ids = Array.from(new Set(ids));
                return ids;
            },
            onCheckboxChange(e) {
                this.checkData = e.records;
                if (this.validatorCheckData().length > 1) {
                    tipsBar(this, 'custom', 'warning', `只能合并相同品种的订单, 当前已选择${this.validatorCheckData().length}个品种!`);
                }
            },
            onStateChange() {
                this.searchParams.pageNo = 1;
                this.checkData = [];
                this.getListRequest();
            },
            onVisibleChangeOfSaveDialogState(e) {
                this.saveDialogState = e;
            },
            onReleaseBtn(row) {
                this.checkData = [row];
                this.releaseDialogState = true;
                // this.checkData = [row];
                // this.onJumpOrder();
            },
            onJumpOrder() {
                if (this.checkData.length) {
                    if (this.validatorCheckData().length === 1) {
                        this.releaseDialogState = true;
                        /* this.$toOtherRouter({
                            name: 'addPrdOrder',
                            query: {
                                saleOrderProductIds: this.checkData.map(x => x.id).join(',')
                            }
                        });*/
                    } else {
                        tipsBar(this, 'custom', 'warning', `只能合并相同品种的订单, 当前已选择${this.validatorCheckData().length}个品种!`);
                    }
                } else {
                    tipsBar(this, 'checkbox');
                }
            },
            onDropdownChange(type, { id, saleOrderId }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem.code === 'QUERY') {
                    this.pageType = 'detail';
                    this.dataId = saleOrderId;
                    this.saveDialogState = true;
                } else {
                    this.$confirm(`确定'${optionItem.name}'吗？`, '提示', { type: 'warning' }).then(() => {
                        optionItem.api({
                            id
                        }).then(res => {
                            if (res.data.status === 200) {
                                this.getListRequest();
                            }
                        });
                    }).catch(() => {});
                }
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getStateBarCountRequest() {
                return productionSaleOrderGetStateCount().then(res => {
                    if (res.data.status === 200) {
                        this.saleOrderStateList = this.saleOrderStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.auditState) {
                                    x.count = k.count;
                                }
                            });
                            return x;
                        });
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailPrdOrder',
                    query: {
                        id: row.id
                    }
                });
            },
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.serviceStateList === -1) {
                    params.serviceStateList = [];
                } else {
                    params.serviceStateList = [params.serviceStateList];
                }
                return this.apiItem['page'](params).then(res => {
                    this.getStateBarCountRequest();
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            onAddBtn() {
                this.pageType = 'add';
                this.dataId = null;
                this.saveDialogState = true;
                // this.$toOtherRouter({ name: 'addPrdOrder' });
            },
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row.saleOrderId;
                this.saveDialogState = true;
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
